package com.hctforgreen.greenservice;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.BaseEntity;
import com.hctforgreen.greenservice.model.KeywordListEntity;
import com.hctforgreen.greenservice.model.KeywordListEntity.KeywordEntity;
import com.hctforgreen.greenservice.model.VideoTypeEntity;
import com.hctforgreen.greenservice.ui.adapter.SearchHistoryListAdapter;
import com.hctforgreen.greenservice.ui.adapter.VideoTypesAdapter;
import com.hctforgreen.greenservice.ui.widget.PullToRefreshListView;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.KeyboardUtil;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;
import com.hctforgreen.greenservice.utils.ThemeStoreUtil;
import com.hctforgreen.greenservice.utils.VideoSearchStoreUtil;

/**
 * 视频分类页面
 * 
 * @author denghb
 * 
 */
public class VideoTypesActivity extends ParentActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_video_detail);
		initSkinLayout();
		initTitleButtonBar();
		initRightButton();
		initSearchBar();
		initDataAndWindow();

	}

	private void initRightButton() {
		final Button download = (Button) findViewById(R.id.btn_right_first);
		final Button history = (Button) findViewById(R.id.btn_right);

		download.setBackgroundResource(R.drawable.btn_video_download);
		download.setVisibility(View.VISIBLE);

		history.setBackgroundResource(R.drawable.btn_pwd_history_selector);
		history.setVisibility(View.VISIBLE);

		history.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(VideoTypesActivity.this,
						VideoHistoryActivity.class);
				startActivity(intent);

			}
		});

		download.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(VideoTypesActivity.this,
						VideoDownloadActivity.class));
			}
		});

	}

	private void initDataAndWindow() {
		final View convertView = findViewById(R.id.lyt_parent);
		final PullToRefreshListView listView = (PullToRefreshListView) convertView
				.findViewById(R.id.lst_default_list);
		final View loadView = convertView
				.findViewById(R.id.lyt_default_list_load);

		final Handler handler = new Handler() {
			@Override
			public void dispatchMessage(Message msg) {
				switch (msg.what) {

				case HctConstants.STATUS_FAILD:

					// List<VideoTypeEntity> data = new
					// ArrayList<VideoTypeEntity>();
					// listView.setAdapter(new VideoTypesAdapter(
					// VideoTypesActivity.this, data));
					break;
				case HctConstants.STATUS_SUCCESS:
					HctResult hctResult = (HctResult) msg.obj;
					List<VideoTypeEntity> data = (List<VideoTypeEntity>) hctResult.data;
					if (data != null && data.size() > 0) {

						VideoTypesAdapter typesAdapter = new VideoTypesAdapter(
								VideoTypesActivity.this, data);
						listView.setAdapter(typesAdapter);
					}
					break;

				default:
					break;
				}
				loadView.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				super.dispatchMessage(msg);
			}
		};

		loadView.setVisibility(View.VISIBLE);
		new Thread() {
			public void run() {
				HctController controller = new HctController(
						VideoTypesActivity.this);
				try {
					HctResult hctResult = controller
							.getVideoTypeList(LoginResultStoreUtil
									.get(getApplicationContext()).personId);
					handler.sendMessage(handler.obtainMessage(
							HctConstants.STATUS_SUCCESS, hctResult));
				} catch (Exception e) {
					handler.sendEmptyMessage(HctConstants.STATUS_FAILD);
					e.printStackTrace();
				}

			};
		}.start();

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (setHistoryViewGone()) {
				return true;
			}
			return super.onKeyDown(keyCode, event);
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	private boolean setHistoryViewGone() {
		final View historyView = findViewById(R.id.lyt_search_history);
		if (historyView.getVisibility() == View.VISIBLE) {
			historyView.setVisibility(View.GONE);
			clearFocus();
			return true;
		}
		return false;
	}

	private void initTitleButtonBar() {

		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(getString(R.string.play_video_title));

		final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (getIntent().getBooleanExtra("fromMain", false)) {
					startActivity(new Intent(VideoTypesActivity.this,
							MainActivityV2.class));

					finish();
				} else {
					finish();
				}

			}
		});

	}

	public static class HightLightEntity extends BaseEntity {
		private static final long serialVersionUID = -9042256048143460873L;
		public String sContents = "";
		public int iCount = 0;
	}

	private void initSearchHistroyLv(final EditText searchInputEt) {
		final LinearLayout searchHistoryLyt = (LinearLayout) findViewById(R.id.lyt_search_history);
		ListView searchHistoryLv = (ListView) findViewById(R.id.lst_default_list_search);

		// HctApplication application = (HctApplication) getApplication();
		// DbKeywordController dbKeywordController = new DbKeywordController(
		// application.getDbKeywordAdapter());

		final KeywordListEntity listEntity = new KeywordListEntity();
		String names = VideoSearchStoreUtil.get(getApplicationContext());
		if (names != null && names.trim().length() > 0) {
			String[] nameArr = names.split(VideoSearchStoreUtil.NAME_DIVIDER);

			if (nameArr != null && names.length() > 0) {
				listEntity.dataList = new ArrayList<KeywordListEntity.KeywordEntity>();
				for (String name : nameArr) {
					if (name != null && name.trim().length() > 0) {
						KeywordEntity entity = new KeywordEntity();
						entity.keyword = name;
						listEntity.dataList.add(entity);
					}
				}
			}

		}

		// final KeywordListEntity listEntity = dbKeywordController
		// .getKeywordListEntity();
		if (listEntity.dataList != null && listEntity.dataList.size() > 0) {

			searchHistoryLyt.setVisibility(View.VISIBLE);
		} else if (listEntity.dataList == null || listEntity.dataList.isEmpty()) {
			searchHistoryLyt.setVisibility(View.GONE);
			return;
		}
		new SearchHistoryListAdapter(VideoTypesActivity.this, searchHistoryLv,
				listEntity.dataList, 1);
		searchHistoryLv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				KeywordEntity entity = listEntity.dataList.get(position);
				searchInputEt.setText(entity.keyword);
				setHistoryViewGone();
				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(VideoTypesActivity.this);
				clearFocus();
				Intent intent = new Intent(VideoTypesActivity.this,
						VideoDetailsActivity.class);
				intent.putExtra("searchName", entity.keyword);
				intent.putExtra("typeName", entity.keyword);
				startActivity(intent);
			}

		});
	}

	private void clearFocus() {

		/**
		 * 使用EditText左侧的ImageView抢Focus
		 */
		ImageView searchIconIv = (ImageView) findViewById(R.id.iv_search_icon);
		searchIconIv.requestFocus();

		final EditText searchInputEt = (EditText) findViewById(R.id.et_search_input);
		searchInputEt.clearFocus();
	}

	private void initSearchBar() {

		final EditText searchInputEt = (EditText) findViewById(R.id.et_search_input);
		final ImageButton clearBtn = (ImageButton) findViewById(R.id.btn_clear);

		searchInputEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				String sInput = searchInputEt.getText().toString().trim();
				if (sInput.equals("")) {
					clearBtn.setVisibility(View.GONE);
				} else if (!sInput.equals("")) {
					clearBtn.setVisibility(View.VISIBLE);
				}
			}

		});
		searchInputEt.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (!hasFocus) {
					setHistoryViewGone();
				} else if (hasFocus) {
					initSearchHistroyLv(searchInputEt);
				}

			}
		});

		searchInputEt.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_SEARCH
						|| keyCode == KeyEvent.KEYCODE_UNKNOWN
						|| keyCode == KeyEvent.KEYCODE_ENTER) {
					setHistoryViewGone();

					insert2Share(searchInputEt);

					KeyboardUtil keyboardUtil = new KeyboardUtil();
					keyboardUtil.hideSoftKeyboard(v);
					clearFocus();
					String searchName = searchInputEt.getText().toString();
					if (searchName.trim().length() > 0) {
						Intent intent = new Intent(VideoTypesActivity.this,
								VideoDetailsActivity.class);
						intent.putExtra("searchName", searchName);
						intent.putExtra("typeName", searchName);
						startActivity(intent);
					}

					return true;
				}
				return false;
			}

			private void insert2Share(final EditText searchInputEt) {
				String sInput = searchInputEt.getEditableText().toString()
						.trim();
				if (sInput.equals("")) {
					return;
				}
				String names = VideoSearchStoreUtil
						.get(getApplicationContext());
				names += VideoSearchStoreUtil.NAME_DIVIDER + sInput;

				VideoSearchStoreUtil.save(getApplicationContext(), names);
			}

		});

		clearBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				searchInputEt.setText("");
				setHistoryViewGone();

				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(v);
				clearFocus();
			}
		});

	}

	@Override
	public void onBackPressed() {

		if (getIntent().getBooleanExtra("fromMain", false)) {
			startActivity(new Intent(VideoTypesActivity.this,
					MainActivityV2.class));
			finish();
		} else {
			finish();
		}

	}

}
